﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using MG.SmartHMI.Common;
using MG.SmartHMI.Domain;
using MG.SmartHMI.Entity.DAO;
using MG.Util.Log;
using SqlSugar.Extensions;

namespace MG.SmartHMI.Model
{
    public partial class SwitchViewModel : BaseItemsControl
    {
        public SwitchViewModel(RegisterConfig data) : base(data)
        {
        }

        public SwitchViewModel() : base()
        {
        }

        #region Switch

        [ObservableProperty]
        private bool isSwitchOn;

        [RelayCommand]
        private void SwitchOut()
        {
            Task.Run(() =>
            {
                ModbusCtrl.Instance.UnitWrite(RegisterData.DataType, RegisterData.Address, IsSwitchOn.ToString());
                EventBus.Default.Log(new LogInfo($"写入 [{RegisterData.Address}]  值 [{IsSwitchOn}]"));
            });
        }

        public override void UpdateRead()
        {
            IsSwitchOn = ModbusCtrl.Instance.UnitWrite(RegisterData.DataType, RegisterData.Address, IsSwitchOn.ToString()).ObjToBool();
            EventBus.Default.Log(new LogInfo($"读取 [{RegisterData.Address}]  值 [{IsSwitchOn}]", LogLevel.Trace));

        }

        public override void UpdateWrite()
        {
            ModbusCtrl.Instance.UnitWrite(RegisterData.DataType, RegisterData.Address, IsSwitchOn.ToString());
        }

        #endregion Switch
    }
}